using UnityEngine;
using TMPro;

/// <summary>
/// APIConfig: stores runtime API keys + endpoints in PlayerPrefs (local only).
/// - Do NOT commit keys to git. Clear inspector fields before committing scenes/prefabs.
/// - Call SaveConfig() from your "Save" button in the UI.
/// - Call ClearSavedKeys() to wipe saved keys locally.
/// </summary>
public class APIConfig : MonoBehaviour
{
    public static APIConfig Instance;

    [Header("UI Fields")]
    public TMP_InputField chatKeyInput;
    public TMP_InputField chatEndpointInput;
    public TMP_InputField chatModelInput;
    public TMP_InputField imageKeyInput;
    public TMP_InputField imageEndpointInput;
    public TMP_InputField imageModelInput; // optional, for image model id

    [Header("Runtime Values")]
    [HideInInspector] public string chatApiKey;
    [HideInInspector] public string chatEndpoint;
    [HideInInspector] public string chatModel;
    [HideInInspector] public string imageApiKey;
    [HideInInspector] public string imageEndpoint;
    [HideInInspector] public string imageModel;

    // PlayerPrefs keys (unique-ish)
    private const string PK_CHAT_KEY = "IWG_CHAT_KEY_v1";
    private const string PK_CHAT_ENDPOINT = "IWG_CHAT_ENDPOINT_v1";
    private const string PK_CHAT_MODEL = "IWG_CHAT_MODEL_v1";
    private const string PK_IMAGE_KEY = "IWG_IMAGE_KEY_v1";
    private const string PK_IMAGE_ENDPOINT = "IWG_IMAGE_ENDPOINT_v1";
    private const string PK_IMAGE_MODEL = "IWG_IMAGE_MODEL_v1";

    void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject); // persist between scenes
        }
        else
        {
            Destroy(gameObject);
            return;
        }

        // Load saved keys into runtime fields and UI
        LoadFromPlayerPrefs();
        PopulateInputFields();
    }

    /// <summary>
    /// Save current values from UI into runtime variables AND PlayerPrefs.
    /// Hook this to the "Save" button.
    /// </summary>
    public void SaveConfig()
    {
        // prefer UI value if present, otherwise keep runtime value
        if (chatKeyInput != null && !string.IsNullOrEmpty(chatKeyInput.text))
            chatApiKey = chatKeyInput.text.Trim();
        if (chatEndpointInput != null && !string.IsNullOrEmpty(chatEndpointInput.text))
            chatEndpoint = chatEndpointInput.text.Trim();
        if (chatModelInput != null && !string.IsNullOrEmpty(chatModelInput.text))
            chatModel = chatModelInput.text.Trim();
        if (imageKeyInput != null && !string.IsNullOrEmpty(imageKeyInput.text))
            imageApiKey = imageKeyInput.text.Trim();
        if (imageEndpointInput != null && !string.IsNullOrEmpty(imageEndpointInput.text))
            imageEndpoint = imageEndpointInput.text.Trim();
        if (imageModelInput != null && !string.IsNullOrEmpty(imageModelInput.text))
            imageModel = imageModelInput.text.Trim();

        SaveToPlayerPrefs();
    }

    // --- PlayerPrefs helpers ---

    private void SaveToPlayerPrefs()
    {
        // Optionally obfuscate with Base64 (this is NOT encryption; comment out if undesired)
        // PlayerPrefs.SetString(PK_CHAT_KEY, System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(chatApiKey ?? "")));
        // Example uses plain storage:
        PlayerPrefs.SetString(PK_CHAT_KEY, chatApiKey ?? "");
        PlayerPrefs.SetString(PK_CHAT_ENDPOINT, chatEndpoint ?? "");
        PlayerPrefs.SetString(PK_CHAT_MODEL, chatModel ?? "");
        PlayerPrefs.SetString(PK_IMAGE_KEY, imageApiKey ?? "");
        PlayerPrefs.SetString(PK_IMAGE_ENDPOINT, imageEndpoint ?? "");
        PlayerPrefs.SetString(PK_IMAGE_MODEL, imageModel ?? "");
        PlayerPrefs.Save();
        Debug.Log("[APIConfig] Saved API configuration to PlayerPrefs (local only).");
    }

    private void LoadFromPlayerPrefs()
    {
        // If Base64 obfuscation used, decode:
        // string ck = PlayerPrefs.GetString(PK_CHAT_KEY, "");
        // if (!string.IsNullOrEmpty(ck)) chatApiKey = System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(ck));

        chatApiKey = PlayerPrefs.GetString(PK_CHAT_KEY, "");
        chatEndpoint = PlayerPrefs.GetString(PK_CHAT_ENDPOINT, "");
        chatModel = PlayerPrefs.GetString(PK_CHAT_MODEL, "");
        imageApiKey = PlayerPrefs.GetString(PK_IMAGE_KEY, "");
        imageEndpoint = PlayerPrefs.GetString(PK_IMAGE_ENDPOINT, "");
        imageModel = PlayerPrefs.GetString(PK_IMAGE_MODEL, "");
    }

    private void PopulateInputFields()
    {
        // Put runtime values into UI so user sees them (if UI hooked)
        if (chatKeyInput != null) chatKeyInput.text = chatApiKey;
        if (chatEndpointInput != null) chatEndpointInput.text = chatEndpoint;
        if (chatModelInput != null) chatModelInput.text = chatModel;
        if (imageKeyInput != null) imageKeyInput.text = imageApiKey;
        if (imageEndpointInput != null) imageEndpointInput.text = imageEndpoint;
        if (imageModelInput != null) imageModelInput.text = imageModel;
    }

    /// <summary>
    /// Wipe saved keys locally. Useful for testing or to remove local secrets.
    /// This does not touch remote APIs or rotate keys.
    /// </summary>
    public void ClearSavedKeys()
    {
        PlayerPrefs.DeleteKey(PK_CHAT_KEY);
        PlayerPrefs.DeleteKey(PK_CHAT_ENDPOINT);
        PlayerPrefs.DeleteKey(PK_CHAT_MODEL);
        PlayerPrefs.DeleteKey(PK_IMAGE_KEY);
        PlayerPrefs.DeleteKey(PK_IMAGE_ENDPOINT);
        PlayerPrefs.DeleteKey(PK_IMAGE_MODEL);
        PlayerPrefs.Save();

        // Clear runtime and UI values
        chatApiKey = chatEndpoint = chatModel = imageApiKey = imageEndpoint = imageModel = "";
        PopulateInputFields();

        Debug.Log("[APIConfig] Cleared saved API configuration from PlayerPrefs.");
    }
}
